import { Request, Response } from 'express';
import { db } from '../../database/index';
import { menuItem } from './menuType';

export const menu = {
    // 获取menuList的数据
    getMenuList: (req: Request, res: Response) => {
        const sqlMenu = 'select * from ev_menulist';
        db.query(sqlMenu, (err, result) => {
            if (err) return res.send(err);
            if (result.length < 0) return res.send({
                status: 1,
                message: '获取menuList失败，请重试！',
                data: null
            });

            /**
             * 获取到全部的数据后，我们需要处理成前端能用的数据，在返回给前端
             */
            if (result.length > 0) {
                let resArr: menuItem[] = [];
                result.map((item: menuItem) => {
                    if (!item.p_id) {
                        item['children'] = [];
                        resArr.push(item);
                    }
                    if (item.p_id) {
                        resArr.map(jtem => {
                            if (item.p_id === jtem.id) {
                                jtem['children'].push(item);
                            }
                        });
                    }
                });

                res.send({
                    status: 0,
                    message: '获取menuList成功！',
                    data: [...resArr]
                });
            }
        });
    }
}